﻿

namespace Huirui.Cavan.Core.Helper
{
    using System;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Drawing.Imaging;
    using System.IO;

    public class CutPhotoHelper
    {
        /// <summary>
        /// 截取图片
        /// </summary>
        /// <param name="pPath">原文件</param>
        /// <param name="pSavedPath">保存文件</param>
        /// <param name="pPartWidth">截取宽</param>
        /// <param name="pPartHeight">截取高</param>
        /// <param name="pOrigStartPointX">距离顶部</param>
        /// <param name="pOrigStartPointY">距离左边</param>
        /// <param name="imageWidth">实际宽</param>
        /// <param name="imageHeight">实际高</param>
        /// <returns></returns>
        public static Bitmap CutPic(Image originalImg, int pPartWidth, int pPartHeight, int pOrigStartPointX, int pOrigStartPointY, int imageWidth, int imageHeight)
        {
            return CutPic(originalImg, 0, 0, pPartWidth, pPartHeight, pOrigStartPointX, pOrigStartPointY, imageWidth, imageHeight, null, 0);
        }
        /// <summary>
        /// 截取图片
        /// </summary>
        /// <param name="pPath">原文件</param>
        /// <param name="pSavedPath">保存文件</param>
        /// <param name="pPartStartPointX">0</param>
        /// <param name="pPartStartPointY">0</param>
        /// <param name="pPartWidth">截取宽</param>
        /// <param name="pPartHeight">截取高</param>
        /// <param name="pOrigStartPointX">距离顶部</param>
        /// <param name="pOrigStartPointY">距离左边</param>
        /// <param name="imageWidth">实际宽</param>
        /// <param name="imageHeight">实际高</param>
        /// <param name="mark">水印文字</param>
        /// <param name="fontSize">水印文字大小</param>
        /// <returns></returns>
        private static Bitmap CutPic(Image originalImg, int pPartStartPointX, int pPartStartPointY, int pPartWidth, int pPartHeight, int pOrigStartPointX, int pOrigStartPointY, int imageWidth, int imageHeight, string mark, int fontSize)
        {
            Bitmap partImg = new Bitmap(pPartWidth, pPartHeight);
            Rectangle destRect = new Rectangle(new Point(pPartStartPointX, pPartStartPointY), new Size(pPartWidth, pPartHeight));//目标位置
            Rectangle origRect = new Rectangle(new Point(pOrigStartPointX, pOrigStartPointY), new Size(pPartWidth, pPartHeight));//原图位置（默认从原图中截取的图片大小等于目标图片的大小）
            fontSize = fontSize > 0 ? fontSize : 1;


            using (Graphics graphics = Graphics.FromImage(partImg))
            {
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                
                using (Graphics G = Graphics.FromImage(partImg))
                {
                    ///文字水印  
                    Font f = new Font("Lucida Grande", fontSize);
                    Brush b = new SolidBrush(Color.Gray);
                    G.Clear(Color.White);
                    G.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    G.SmoothingMode = SmoothingMode.HighQuality;

                    if (originalImg.Width == imageWidth && originalImg.Height == imageHeight)
                    {
                        graphics.DrawImage(originalImg, destRect, origRect, GraphicsUnit.Pixel);
                    }
                    else
                    {
                        using (Bitmap thumimg = MakeThumbnail(originalImg, imageWidth, imageHeight))
                        {
                            graphics.DrawImage(thumimg, destRect, origRect, GraphicsUnit.Pixel);
                        }
                    }
                    if (!string.IsNullOrEmpty(mark))
                        G.DrawString(mark, f, b, pPartWidth - mark.Length * fontSize - 5, pPartHeight - fontSize - 5);
                }
            }

            return partImg;
        }
        /// <summary>
        /// 缩放
        /// </summary>
        /// <param name="fromImg">图片</param>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>
        /// <returns></returns>
        public static Bitmap MakeThumbnail(Image fromImg, int width, int height)
        {
            Bitmap bmp = new Bitmap(width, height);
            int ow = fromImg.Width;
            int oh = fromImg.Height;

            //新建一个画板
            Graphics g = Graphics.FromImage(bmp);

            //设置高质量插值法
            g.InterpolationMode = InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = SmoothingMode.HighQuality;
            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);

            g.DrawImage(fromImg
                , new Rectangle(0, 0, width, height)
                , new Rectangle(0, 0, ow, oh)
                , GraphicsUnit.Pixel);

            return bmp;
        }
        #region 图片处理
        /// <summary>
        /// 获取缩略图的长与宽
        /// </summary>
        /// <param name="minwidth">原宽</param>
        /// <param name="minheight">原长</param>
        /// <param name="width">宽</param>
        /// <param name="height">长</param>
        /// <returns>长宽整数对</returns>
        public static Size NewSize(int minwidth, int minheight, int width, int height)
        {
            double w = 0.0;
            double h = 0.0;
            double sw = Convert.ToDouble(width);
            double sh = Convert.ToDouble(height);
            double mw = Convert.ToDouble(minwidth);
            double mh = Convert.ToDouble(minheight);

            if (sw < mw && sh < mh)
            {
                w = sw;
                h = sh;
            }
            else if ((sw / sh) > (mw / mh))
            {
                w = minwidth;
                h = (w * sh) / sw;
            }
            else
            {
                h = minheight;
                w = (h * sw) / sh;
            }

            return new Size(Convert.ToInt32(w), Convert.ToInt32(h));
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="filename">上传图片数据源</param>
        /// <param name="minwidth">缩略图宽</param>
        /// <param name="minheight">缩略图高</param>
        /// <param name="FileName">上传到DISK文件夹下目录</param>
        /// <param name="type">图片类型,BOOL型变量,true为jpg,反之为gif</param>
        /// <returns>返回当前图片名</returns>
        public static string SendToSmallImage(Stream _stream, int minwidth, int minheight, string FileName, bool type)
        {
            System.Drawing.Image img = System.Drawing.Image.FromStream(_stream);
            //System.Drawing.Image img = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(filename));
            ImageFormat imgformat = img.RawFormat;

            Size newSize = NewSize(minwidth, minheight, img.Width, img.Height);

            Bitmap bm = new Bitmap(newSize.Width, newSize.Height);
            Graphics g = Graphics.FromImage(bm);

            // 设置画布的描绘质量
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
            g.Dispose();

            // 以下代码为保存图片时，设置压缩质量
            EncoderParameters encoderParams = new EncoderParameters();
            long[] quality = new long[1];
            quality[0] = 100;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;

            //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象。
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo jpegICI = null;
            ImageCodecInfo GIFICI = null;
            ImageCodecInfo allICI = null;
            for (int x = 0; x < arrayICI.Length; x++)
            {
                if (arrayICI[x].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[x];//设置JPEG编码
                }

                if (arrayICI[x].FormatDescription.Equals("GIF"))
                {
                    GIFICI = arrayICI[x];//设置GIF编码
                }
            }

            string stringpath = null;
            string imagename = DateTime.Now.ToString("yyMMddmmss");
            if (type)
            {
                stringpath = "/Disk/" + FileName + "/" + imagename + ".jpg";
                allICI = jpegICI;
                imagename = imagename + ".jpg";
            }
            else
            {
                stringpath = "/Disk/" + FileName + "/" + imagename + ".gif";
                allICI = GIFICI;
                imagename = imagename + ".gif";
            }

            try
            {
                bm.Save(System.Web.HttpContext.Current.Server.MapPath(stringpath), allICI, encoderParams);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                img.Dispose();
                bm.Dispose();
            }

            return imagename;
        }
        #endregion
    }
}